<template>
  <el-card>
    <div slot="header">
      <el-button @click="handleAdd">添加资源分类</el-button>
      <el-button @click="$router.push({name:'resource'})">返回资源管理</el-button>
    </div>
    <el-table :data="items" style="width: 100%" v-loading="loading">
      <el-table-column type="index" label="编号" />
      <el-table-column prop="name" label="分类名称" />
      <el-table-column prop="sort" label="排序" />
      <el-table-column fixed="right" label="操作" min-width="120">
        <template slot-scope="scope">
          <el-button @click.native.prevent="handleEdit(scope.row)" size="mini">
            编辑
          </el-button>
          <el-button
            @click.native.prevent="handleDelete(scope.row)"
            type="danger"
            size="mini"
          >
            移除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <PromiseDialogFormCreateOrEdit ref='dialogAdd' />
    <PromiseDialogFormCreateOrEdit ref='dialogEdit' :id="editItemId" />
  </el-card>
</template>
<script lang="ts">
import Vue from 'vue'
import { getAllCategory, removeCategory } from '@/services/resource'
import { wrapAsyncWithLoading } from '@/utils/helper'
import PromiseDialogFormCreateOrEdit from './components/PromiseDialogFormCreateOrEdit.vue'
import { HasId, ID } from '@/types'
export default Vue.extend({
  name: 'resource-category-index',
  components: {
    PromiseDialogFormCreateOrEdit
  },
  data () {
    return {
      items: [],
      loading: true,
      editItemId: '' as ID
    }
  },
  created () {
    wrapAsyncWithLoading(this, 'loading', 'loadItems')
    this.loadItems()
  },
  methods: {
    async loadItems () {
      const { data } = await getAllCategory()
      if (data.code === '000000') {
        this.items = data.data
      }
    },
    async handleAdd () {
      try {
        await (this.$refs.dialogAdd as PromiseDialog).open()
      } catch (error) {
        return
      }

      this.$message.success('添加成功')
      this.loadItems()
    },
    async handleEdit (item: HasId) {
      this.editItemId = item.id
      // 子组件多久能拿到？
      try {
        await (this.$refs.dialogEdit as PromiseDialog).open()
      } catch (error) {
        if (typeof error === 'string') {
          this.$message.error(error)
          this.loadItems()
        }
        return
      }
      this.$message.success('编辑成功')
      this.loadItems()
    },
    async handleDelete (item: HasId) {
      try {
        await this.$confirm('确认删除分类么')
      } catch (error) {
        return
      }
      const { data } = await removeCategory(item.id)
      if (data.code === '000000') {
        this.$message.success('已删除')
        this.loadItems()
      }
    }
  }
})
</script>
